package og.jaaksi.test.gridview;

import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;

import java.util.ArrayList;
import java.util.List;

/**
 * Created by Fcy on 2015/12/17.
 * 不同于系统ArrayAdapter
 * 如果为null，是否要new
 * notifyDataSetChanged的作用，
 */
public abstract class ArrayAdapter<T> extends BaseAdapter {
    protected List<T> mInfos = new ArrayList<>();

    protected LayoutInflater mInflater;
    protected Context mContext;

    protected OnItemClickListener<T> mOnItemClickListener;

    public ArrayAdapter(Context context) {
        this(context, null);
    }

    public ArrayAdapter(Context context, OnItemClickListener<T> onItemClickListener) {
        mInflater = LayoutInflater.from(context);
        this.mContext = context;
        this.mOnItemClickListener = onItemClickListener;
    }

    public void setOnItemClickListener(OnItemClickListener<T> onItemClickListener) {
        this.mOnItemClickListener = onItemClickListener;
    }

    public List<T> getDatas() {
        return mInfos;
    }

    public void setDatas(List<T> list) {
        mInfos.clear();
        addAll(list);
        notifyDataSetChanged();
    }

    public void add(T t) {
        mInfos.add(t);
    }

    public void addAll(List<T> list) {
        if (list != null) {
            mInfos.addAll(list);
        }
//        notifyDataSetChanged();
    }

    public void clear() {
        mInfos.clear();
    }

    @Override
    public int getCount() {
        return mInfos.size();
    }

    @Override
    public T getItem(int position) {
        return mInfos.get(position);
//        return position >= mInfos.size() ? null : mInfos.get(position);
    }

    @Override
    public long getItemId(int position) {
        return position;
    }

    @Override
    public abstract View getView(int position, View convertView, ViewGroup parent);

    /**
     * 通过这个listener可以将adapter中的点击事件移到Activity中处理，也可以I
     */
    protected class MyOnClickListener implements View.OnClickListener {
        protected int position;

        public MyOnClickListener(int position) {
            this.position = position;
        }

        @Override
        public void onClick(View v) {
            if (mOnItemClickListener != null) {
                mOnItemClickListener.clickItem(getItem(position), v, position);
            }
        }
    }

    public interface OnItemClickListener<T> {
        void clickItem(T t, View view, int position);
    }
}
